package com.stef.MMH;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.stef.MMH.datatypes.User;

public class LoginServlet extends HttpServlet {
	User user;
	HttpServletRequest req;
	HttpServletResponse resp;
	EntityManager em = EmfHolder.getEntityManager();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		this.req = req;
		this.resp = resp;
		boolean validSubmission = checkParams();

		if (validSubmission) {
			validSubmission = processLogin();
		}

		if (validSubmission) {
			successfulLoginHtmlWrite();
			createSession();
		} else {
			resp.getWriter().println("Try AGAIN, LOLS!!");
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

	private boolean checkParams() throws IOException {
		boolean validParams = true;
		Map<String, String[]> paramMap = req.getParameterMap();
		boolean validSubmission = true;
		for (Map.Entry<String, String[]> en : paramMap.entrySet()) {
			if (en.getValue()[0].length() < 1) {
				resp.getWriter().println("Missing value for " + en.getKey());
				validSubmission = false;
			}
		}
		return validParams;

	}

	private boolean processLogin() throws IOException {

		boolean validLogin = true;
		String email = "None";
		String password = "None";
		try {
			email = URLEncoder.encode(req.getParameter("email"), "UTF-8");
			password = URLEncoder.encode(req.getParameter("password"), "UTF-8");
		} catch (Exception e) {
			validLogin = false;
			e.printStackTrace();
			return validLogin;

		}
		Query q = em.createQuery("SELECT u from User u WHERE u.email = \""
				+ email + "\"");
		try {
			user = (User) q.getSingleResult();
		} catch (NonUniqueResultException e) {
			e.printStackTrace();
			validLogin = false;
		} catch (NoResultException nre) {
			resp.getWriter().println("email does not exist!");
			validLogin = false;
		}

		if (validLogin) {
			validLogin = user.getPasswordHash().equals(password);
		}

		return validLogin;
	}

	protected void successfulLoginHtmlWrite() throws IOException {

		StringBuilder sb = new StringBuilder();
		sb.append("<html><body><h1>Good Job!</h1>"
				+ "\n"
				+ "<p>You Logged in, "
				+ URLDecoder.decode(user.getRealName(), "UTF-8")
				+ "</p>"
				+ '\n'
				+ "<meta HTTP-EQUIV=\"REFRESH\" content=\"5; url=managemyhouse\">"
				+ "</body></html>");

		resp.getWriter().print(sb.toString());

	}

	protected void createSession() {
		HttpSession session = req.getSession(true);
		synchronized (session) {
			if (!session.isNew()) {
				session.removeAttribute("USER");
				session.setAttribute("USER", user);
			}else{
				session.setAttribute("USER", user);
			}
		}

	}

}
